﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication3
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //页面加载
            if (!IsPostBack )
            {
                FillData();
            }
        }

        //为Griv3填充数据
        private void FillData()
        {
            var sql = "select * from Articles";
            var db = DbHelp.GetData(sql);
            Griv3.DataSource = db;
            Griv3.DataBind();
        }

        //取消编辑
        protected void Griv3_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            Griv3.EditIndex = -1;
            FillData();
        }

        //删除
        protected void Griv3_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var Id = GetCell(e.RowIndex, 0);
            var sql = string.Format("delete from Articles where id={0}", Id);
            DbHelp.CDU(sql);
            Griv3.EditIndex = -1;
            FillData();
        }

        //编辑
        protected void Griv3_RowEditing(object sender, GridViewEditEventArgs e)
        {
            Griv3.EditIndex = e.NewEditIndex;
            FillData();
        }

        //更改
        protected void Griv3_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //判断Id是否存在
            var idstring = GetCell(e.RowIndex, 0);
            var isok = int.TryParse(idstring ,out int id);
            var Id = GetCell(e.RowIndex, 0);
            var Title = GetCell(e.RowIndex, 1);
            var Content = GetCell(e.RowIndex, 2);
            var Author = GetCell(e.RowIndex, 3);
            var Remarks = GetCell(e.RowIndex, 4);
            if (isok)
            {
                //更改sql语句
                var sql = string.Format("update Articles set Title='{0}',Content='{1}',Author='{2}',Remarks='{3}' where id='{4}'", Title, Content, Author, Remarks, Id);
                DbHelp.CDU(sql);
            }
            else
            {
                //添加
                var sql = string.Format("insert into Articles (Title,Content,Author,Remark)values('{0}', '{1}', '{2}', '{3}') ", Title, Content, Author, Remarks);
                DbHelp.CDU(sql);
            }
            Griv3.EditIndex = -1;
            FillData();
        }

        //获取单元格数据
        private object GetCell(int rowIndex, int columnIndex)
        {
            //获取行索引为rowIndex和列索引为colIndex的单元格
            var cell = Griv3.Rows[rowIndex].Cells[columnIndex];
            // 判断这个单元格里面的子控件数量是否大于0
            // 如果大于0就说明有子控件，我们就获取子控件里面的值
            // 如果没有大于0就说明没有子控件，我们就直接获取单元格里面的值
            var res = cell.Controls.Count > 0 ? ((TextBox)cell.Controls[0]).Text : cell.Text;
            return res;
        }

    }
}